import { ref, computed } from 'vue'

export function useFileSelection(emit) {
  // 选中的文件路径集合
  const selectedPaths = ref(new Set())
  
  // 最后选择的文件路径和索引
  const lastSelected = ref(null)
  
  // 选择数量
  const selectionCount = computed(() => selectedPaths.value.size)
  
  // 检查文件是否被选中
  const isSelected = (filePath) => selectedPaths.value.has(filePath)
  
  // 处理文件点击
  const handleFileClick = (event, file, fileList) => {
    const filePath = file.path
    const currentIndex = fileList.findIndex(f => f.path === filePath)
    
    // Shift + 点击处理范围选择
    if (event.shiftKey && lastSelected.value !== null) {
      const lastIndex = fileList.findIndex(f => f.path === lastSelected.value)
      
      if (lastIndex !== -1) {
        const start = Math.min(lastIndex, currentIndex)
        const end = Math.max(lastIndex, currentIndex)
        
        for (let i = start; i <= end; i++) {
          selectedPaths.value.add(fileList[i].path)
        }
      }
    } 
    // 普通点击切换选择状态
    else {
      if (selectedPaths.value.has(filePath)) {
        selectedPaths.value.delete(filePath)
      } else {
        selectedPaths.value.add(filePath)
      }
    }
    
    lastSelected.value = filePath
    emit('update:selected', Array.from(selectedPaths.value))
  }
  
  // 清除选择
  const clearSelection = () => {
    selectedPaths.value.clear()
    lastSelected.value = null
    emit('update:selected', [])
  }
  
  // 更新选择状态
  const updateSelection = (newSelection) => {
    selectedPaths.value = new Set(newSelection)
  }
  
  return {
    selectedPaths,
    selectionCount,
    isSelected,
    handleFileClick,
    clearSelection,
    updateSelection
  }
} 